package com.twu.biblioteca.ui.menus;

import com.twu.biblioteca.app.Library;
import com.twu.biblioteca.app.movie.Movie;
import com.twu.biblioteca.app.user.User;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

public class MovieListMenu extends ItemListMenu{
        private Map<Integer, Movie> movieOptions;
        private BufferedReader bufferedReader;

        public MovieListMenu(BufferedReader bufferedReader) {
            super(bufferedReader);
            this.bufferedReader = bufferedReader;
            movieOptions = new HashMap<Integer, Movie>();

        }

        public String getMenuOptions(Library library) {
            String menuOptions = "";
            menuOptions += "---------------------------------------------\n";
            menuOptions += "AVAILABLE MOVIES\n";
            menuOptions += "---------------------------------------------\n";
            menuOptions += "Please select the movie you wish to check out by entering it's option number:\n";
            menuOptions += listAllMoviesInLibraryWithOptionNumbers(library);
            return menuOptions;
        }

        protected String listAllMoviesInLibraryWithOptionNumbers(Library library) {
            int optionNumber = 1;
            String menuOptions = "";
            for (Movie movie : library.getAvailableMovies()) {
                menuOptions += optionNumber + ". " + movie.getTitle() + "(" + movie.getYear() + ") directed by " + movie.getDirector() + "\n";
                saveMovieToOptionNumber(optionNumber, movie);
                optionNumber += 1;
            }
            return menuOptions;
        }

        private void saveMovieToOptionNumber(int optionNumber, Movie movie) {
            movieOptions.put(optionNumber, movie);
        }

        @Override
        public Library attemptToCheckoutItem(int selection, Library library, User user) {
            return attemptToCheckoutMovie(selection, library, user);
        }


        public Library attemptToCheckoutMovie(int selection, Library library, User user) {
            Movie selectedMovie = movieOptions.get(selection);
            if (selectedMovie != null && library.checkoutMovie(selectedMovie, user)) {
                displaySuccessfulCheckoutMessage();
            } else {
                displaySelectionError();
            }
            return library;
        }

        public void displaySelectionError() {
            System.out.print("That movie is not available.\n");
        }

        public void displaySuccessfulCheckoutMessage() {
            System.out.print("Thank-you! Enjoy the Movie\n");
        }
 }





